import { BetslipItemStatus, BettingOrderType, BetslipBaseType } from '@/types'
import { onUnmounted, watch, computed } from 'vue'
import { BettingOrderStatus } from '@/enums'
import { getBetOrdersStatus } from '@/api/betting'
import { useBetslipStore } from '@/store'
import { isTransition as isTransitionFn } from '@/utils'

export const useBetslip = (item: BetslipBaseType) => {
	const betslipStore = useBetslipStore()

	let timer: any

	const getOrderStatus = async () => {
		let hasResult = false
		try {
			timer && clearTimeout(timer)
			if (item.order?.orderNo) {
				const { data } = await getBetOrdersStatus({
					orderNos: item.order.orderNo
				})
				if (data.length) {
					const order: BettingOrderType = data[0]
					const { status } = order
					if (status === BettingOrderStatus.successed || status === BettingOrderStatus.failed) {
						hasResult = true
						betslipStore.updateStatus(item, order)
					}
				}
			}
		} catch {}
		if (!hasResult) {
			timer = setTimeout(() => getOrderStatus(), 5000)
		}
	}

	watch(
		() => item.status,
		(status) => {
			timer && clearTimeout(timer)
			if (status === BetslipItemStatus.success) {
				timer = setTimeout(() => {
					item.status = BetslipItemStatus.successed
					betslipStore.addSuccess(item)
				}, 500)
			} else if (status === BetslipItemStatus.fail) {
				timer = setTimeout(() => {
					item.status = BetslipItemStatus.failed
				}, 500)
			} else if (status === BetslipItemStatus.confirming) {
				getOrderStatus()
			}
		},
		{ immediate: true }
	)

	onUnmounted(() => timer && clearTimeout(timer))

	const isTransition = computed(() => isTransitionFn(item.status))

	return { isTransition }
}
